
###############################################################################
## CuteTimer
## Speed-run plugin for EventScripts Python
## Officially supported games: CS:S OB
##
## File: utils/fileparser.py
## Author: zoomj
## Description: various file parsing helpers
## Version: 0.1

from __future__ import with_statement
import os

__all__ = [
    'SimpleTextFileParser'
]

class SimpleTextFileParser(object):
    _file_contents = []
    _file_path = ''
    _ignore_comments = False
    
    def __init__(self, file_path, ignore_comments = False):
        self._file_path = file_path
        self._ignore_comments = ignore_comments
        self._load_file()
            
    def _load_file(self):
        with open(self._file_path, 'r') as file_ref:
            if not self._ignore_comments:
                self._file_contents = file_ref.readlines()
            else:
                multiline_comment = False
                for line in file_ref.readlines():
                    if multiline_comment:
                        if '*/' in line:
                            multiline_comment = False
                            continue
                        continue
                    stripped = line.strip()
                    if not len(stripped):
                        continue
                    if (stripped[0] in ('#', ';') or stripped[0:2] == '//'):
                        continue
                    elif '/*' in stripped:
                        if '*/' in stripped:
                            continue
                        if stripped[0:2] == '/*':
                            multiline_comment = True
                            continue
                        else:
                            mlc_found = stripped.find('/*')
                            if mlc_found > 0:
                                text = stripped[0:mlc_found]
                                multiline_comment = True
                                self._file_contents.append(text)
                                continue
                            else:
                                multiline_comment = True
                                continue
                    for comment in ('#', '//', ';'):
                        sc_found = stripped.find(comment)
                        if sc_found > 0:
                            text = stripped[0:sc_found]
                            self._file_contents.append(text)
                            continue
                        else:
                            continue
                    if not len(stripped):
                        continue
                    self._file_contents.append(stripped)
    
    def rehash(self, ignore_comments = False):
        self._load_file()
        
    def read_lines(self):
        return self._file_contents
        